#!/usr/bin/env perl
#
# Copyright (c) 2012-2013 Jeffrey M. Squyres.  All rights reserved.
#
# $COPYRIGHT$
#
# Additional copyrights may follow
# 
# $HEADER$

use strict;

use Data::Dumper;
use Getopt::Long;
use File::Basename;
use Cwd;

# With no effort; see if we can just "require" and find rubyslippers
# files.
sub find_rs_libs_default {
    my $rs_lib = cwd() . "/lib";
    use lib cwd() . "/lib";

    my $ret;
    eval "\$ret = require RubySlippers::Version";
    return ($ret == 1) ? 1 : 0;
}

# If $0 is a path, try adding that do @INC and try "require" again.
sub find_rs_libs_argv0 { 
    my $dir = dirname($0); 
    my @INC_save = @INC;

    # Change to the dir of $0 (because it might be a relative
    # directory) and add the cwd() to @INC
    my $start_dir = cwd();
    chdir($dir);
    my $rs_lib = cwd() . "/lib";
    push(@INC, $rs_lib);
    chdir($start_dir);

    my $ret;
    eval "\$ret = require RubySlippers::Version";
    @INC = @INC_save
        if (1 != $ret);
    return ($ret == 1) ? 1 : 0;
}

# Otherwise, search $ENV[PATH] for rubyslippers, and when you find it,
# add that directory to @INC and try again.
sub find_rs_libs_path {
    my @dirs = split(/:/, $ENV{PATH});
    my @INC_save = @INC;
    my $rs = basename($0);
    my $start_dir = cwd();
    foreach my $dir (@dirs) {
        # If we found the rs executable, add the dir to @INC and
        # see if we can "require".  If require fails, restore @INC
        # and keep trying.
        if (-x "$dir/$rs") {
            chdir($dir);
            chdir("..");
            my $rs_lib = cwd() . "/lib";
            push(@INC, $rs_lib);
            chdir($start_dir);
            my $ret;
            eval "\$ret = require RubySlippers::Version";
            if (1 == $ret) {
                return 1;
            } else {
                @INC = @INC_save;
            }
        }
    }

    # Didn't find it -- doh!
    return 0;
}

BEGIN {
    # Try to find the rubyslippers files.  Assume that the rubyslippers
    # executable is in the base directory for the rubyslippers files.  Try
    # three methods.
    die "Unable to find RubySlippers support libraries"
        if (!find_rs_libs_default() &&
            !find_rs_libs_argv0() &&
            !find_rs_libs_path());
}

# If we get here, then @INC is setup properly and it's safe to "use"
# RubySlippers modules.

########################################################################

# Parse command line options

use RubySlippers::Version;
use RubySlippers::Messages;

my $version_arg;
my $help_arg;
my $foreground_arg = 0;
my $debug_arg = 0;
my $verbose_arg = 1;
my $config_arg;

&Getopt::Long::Configure("bundling");
my $ok = Getopt::Long::GetOptions("version" => \$version_arg,
                                  "config|c=s" => \$config_arg,
                                  "foreground|f!" => \$foreground_arg,
                                  "debug|d!" => \$debug_arg,
                                  "verbose|v!" => \$verbose_arg,
                                  "help|h" => \$help_arg
                                  );

if (!$ok || $help_arg) {
    print "Options:
--version              Show the RubySlippers version
--config FILENAME      Use the specifid RubySlippers config file
                       (default is \$HOME/.rubyslippers.config)
--foreground           Run in the foreground 
                       (default is to fork into background)
--debug                Output lots of debug messages
--verbose              Output a moderate amount of status messages
--help | -h            This help message\n";
    exit(!$ok);
}

if ($version_arg) {
    print "RubySlippers Version $RubySlippers::Version::Major.$RubySlippers::Version::Minor.$RubySlippers::Version::Release\n";
    exit(0);
}

# If we specify debug, then also run in the foreground
$foreground_arg = 1
    if ($debug_arg);
RubySlippers::Messages::Messages($debug_arg, $verbose_arg, 1 - $foreground_arg);

# If no config file was specified, and $HOME/.rubyslippers.config
# exists, use that
my $default_config = "$ENV{HOME}/.rubyslippers.config";
$config_arg = $default_config
    if (!defined($config_arg) && -r $default_config);

########################################################################

# Run the main engine
use RubySlippers::Engine;

my $ret = RubySlippers::Engine::run($foreground_arg, $debug_arg, $config_arg);

# All done!
# JMS For the moment, MDNS still has a thread running.  So don't
# complain about it.
no warnings 'threads';

exit($ret);
